package com.tree.treeoj.judge.strategy;

import cn.hutool.json.JSONUtil;
import com.tree.treeoj.model.dto.question.JudgeCase;
import com.tree.treeoj.model.dto.question.JudgeConfig;
import com.tree.treeoj.judge.codesandbox.model.JudgeInfo;
import com.tree.treeoj.model.entity.Question;
import com.tree.treeoj.model.enums.JudgeInfoMessageEnum;

import java.util.List;

/**
 * @author : Tree Arthur
 * @date: 2023/12/23 0:25
 * @Package: com.tree.treeoj.judge.strategy
 * @Description: 默认策略
 * @version: 1.0
 */
public class DefaultJudgeStrategy implements JudgeStrategy{

    /**
     * 执行判题
     * @param judgeContext 判题上下文
     * @return
     */
    @Override
    public JudgeInfo doJudge(JudgeContext judgeContext) {

        JudgeInfo judgeInfo = judgeContext.getJudgeInfo();
        List<String> inputList = judgeContext.getInputList();
        List<String> outputList = judgeContext.getOutputList();
        Question question = judgeContext.getQuestion();
        List<JudgeCase> judgeCaseList = judgeContext.getJudgeCaseList();

        Long memory = judgeInfo.getMemory();//获取编译内存
        Long time = judgeInfo.getTime();//获取编译时间
        JudgeInfoMessageEnum judgeInfoMessageEnum = JudgeInfoMessageEnum.ACCEPTED;

        JudgeInfo judgeInfoResponse = new JudgeInfo();
        judgeInfoResponse.setMemory(memory);
        judgeInfoResponse.setTime(time);

        if (outputList.size() != inputList.size()){
            judgeInfoMessageEnum = JudgeInfoMessageEnum.WRONG_ANSWER;
            judgeInfoResponse.setMessage(judgeInfoMessageEnum.getValue());
            return judgeInfoResponse;
        }
        //依次判断每一项输出和预期输出是否相等
        for (int i = 0; i < judgeCaseList.size(); i++) {
            JudgeCase judgeCase = judgeCaseList.get(i);
            if (!judgeCase.getOutput().equals(outputList.get(i))){
                judgeInfoMessageEnum = JudgeInfoMessageEnum.WRONG_ANSWER;
                judgeInfoResponse.setMessage(judgeInfoMessageEnum.getValue());
                return judgeInfoResponse;            }
        }
        //判题题目的限制是否符合要求
        String judgeConfigStr = question.getJudgeConfig();//配置
        JudgeConfig judgeConfig = JSONUtil.toBean(judgeConfigStr, JudgeConfig.class);//JSON转对象
        Long needMemoryLimit = judgeConfig.getMemoryLimit();//内存限制
        Long needTimeLimit = judgeConfig.getTimeLimit();//时间限制
        if (memory > needMemoryLimit){//内存溢出
            judgeInfoMessageEnum = JudgeInfoMessageEnum.MEMORY_LIMIT_EXCEEDED;
            judgeInfoResponse.setMessage(judgeInfoMessageEnum.getValue());
            return judgeInfoResponse;        }
        if (time > needTimeLimit){//运行超时
            judgeInfoMessageEnum = JudgeInfoMessageEnum.MEMORY_LIMIT_EXCEEDED;
            judgeInfoResponse.setMessage(judgeInfoMessageEnum.getValue());
            return judgeInfoResponse;
        }

        judgeInfoResponse.setMessage(judgeInfoMessageEnum.getValue());
        return judgeInfoResponse;
    }
}
